package com.learn.scrm;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import com.learn.http.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.util.StreamUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * @author : Yu.Tan
 * @date : 2023/6/5 14:28
 * @desc : **
 */
@Slf4j
public class FileTest {
    public static void main(String[] args) {

    }

    public static void downTwo(String imageUrl){
        try {
            InputStream inputStream = URLUtil.url(imageUrl).openStream();
            byte[] byteArray = StreamUtils.copyToByteArray(inputStream);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }




    public static void downThree(String imageUrl){
        String filePath = "/data/logs/" + System.currentTimeMillis() + ".jpg";
        File tempFile = new File(filePath);
        cn.hutool.http.HttpUtil.downloadFile(imageUrl, tempFile);
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(tempFile);
        } catch (FileNotFoundException e) {
            throw new IllegalArgumentException("文件流操作异常!");
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        JSONObject jsonObject = uploadFile("jpg", fileInputStream, "127.0.0.1:8080/file/upload", null);

    }


    public static void downFour(String imageUrl){

        try {
            URL url = new URL(imageUrl);
            InputStream inputStream = url.openStream();

            // Output stream to save the image to file
            FileOutputStream outputStream = new FileOutputStream("image.jpg");

            // Read bytes from the input stream and write to the output stream
            byte[] buffer = new byte[2048];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * post文件上传
     *
     * @param url              接口地址
     * @param headers          headers参数
     * @param params           参数
     * @param fileKey          服务端接口参数key
     * @param files            文件集合
     */
    public static final MediaType MEDIA_TYPE_MULTIPART_FORM = MediaType.parse("multipart/form-data;");

//    public String postFileUpload(String url, Map<String, String> headers, Map<String, String> params, String fileKey, List<File> files) {
//        String result = "";
//        try {
//            // form 表单形式上传
//            MultipartBody.Builder builder = new MultipartBody.Builder();
//            builder.setType(MultipartBody.FORM);
//
//            //添加参数
//            if (params != null) {
//                for (Map.Entry<String, String> entry : params.entrySet()) {
//                    builder.addFormDataPart(entry.getKey(), entry.getValue());
//                }
//            }
//            //添加文件，并约定key如“upload”作为后台接受的参数key
//            if (files != null) {
//                for (File file : files) {
//                    builder.addFormDataPart(fileKey, file.getName(), RequestBody.create(MEDIA_TYPE_MULTIPART_FORM, file));
//                }
//            }
//            RequestBody requestBody = builder.build();
//            Request.Builder requestBuilder = getRequestBuilder(headers);
//            requestBuilder.addHeader("Content-Type","multipart/form-data;");
//
//            Request request = requestBuilder.url(url).post(requestBody).build();
//            Response response = okHttpClient.newCall(request).execute();
//            if (response != null && response.isSuccessful()) {
//                result = response.body().string();
//            }
//        } catch (Exception e) {
//            log.error("postFileUpload, url = " + url + " , params : " + JSON.toJSONString(params) , e);
//        }
//        return result;
//    }

    public Request.Builder getRequestBuilder(){
        return new Request.Builder();
    }


    /**
     * post文件上传
     *
     * @param url              接口地址
     * @param headers          headers参数
     * @param params           参数
     * @param fileKey          服务端接口参数key
     * @param files            文件集合
     * @param netCall          回调函数
     */
//    public void postFileUploadAsync(String url, Map<String, String> headers, Map<String, String> params, String fileKey, List<File> files) {
//        String result = "";
//        try {
//            // form 表单形式上传
//            MultipartBody.Builder builder = new MultipartBody.Builder();
//            builder.setType(MultipartBody.FORM);
//
//            //添加参数
//            if (params != null) {
//                for (Map.Entry<String, String> entry : params.entrySet()) {
//                    builder.addFormDataPart(entry.getKey(), entry.getValue());
//                }
//            }
//            //添加文件，并约定key如“upload”作为后台接受的参数key
//            if (files != null) {
//                for (File file : files) {
//                    builder.addFormDataPart(fileKey, file.getName(), RequestBody.create(MEDIA_TYPE_MULTIPART_FORM, file));
//                }
//            }
//            RequestBody requestBody = builder.build();
//            Request.Builder requestBuilder = getRequestBuilder(headers);
//            requestBuilder.addHeader("Content-Type","multipart/form-data;");
//
//            Request request = requestBuilder.url(url).post(requestBody).build();
//            Response response = okHttpClient.newCall(request).execute();
//            if (response != null && response.isSuccessful()) {
//                result = response.body().string();
//            }
//        } catch (Exception e) {
//            log.error("postFileUpload, url = " + url + " , params : " + JSON.toJSONString(params) , e);
//        }
//        return result;
//    }

        public static JSONObject uploadFile(String fileName, FileInputStream fileInputStream, String url, Map<String, String> header) {
        try {
            // 构建上传文件内容
            byte[] byteFileContent = new byte[fileInputStream.available()];
            fileInputStream.read(byteFileContent);
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            okhttp3.RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("suffix", fileName,
                            okhttp3.RequestBody.create(MediaType.parse("application/octet-stream"), byteFileContent))
                    .build();
            Request.Builder builder = new Request.Builder()
                    .url(url)
                    .method("POST", requestBody);
            if (header != null) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    builder.addHeader(entry.getKey(), entry.getValue());
                }
            }
            Request request = builder.build();
            Response response = client.newCall(request).execute();
            // 响应内容数据解析
            String responseBodyJson = "";
            if (null != response.body()) {
                responseBodyJson = response.body().string();
            }
            R responseData = JSONObject.parseObject(responseBodyJson, R.class);
            JSONObject jsonObject = (JSONObject) responseData.getData();
            return jsonObject;
        } catch (IOException e) {
            throw new IllegalArgumentException("文件流操作异常!");
        }
    }

    public static void downOne(String imageUrl) {
        try {
            // URL of the image to download
//        String imageUrl = "https://example.com/image.jpg";

            // Create URL object and open input stream to the image
            URL url = new URL(imageUrl);
            InputStream inputStream = url.openStream();

            // Output stream to save the image to file
            FileOutputStream outputStream = new FileOutputStream("image.jpg");

            // Read bytes from the input stream and write to the output stream
            byte[] buffer = new byte[2048];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }

            // Close streams
            inputStream.close();
            outputStream.close();

            System.out.println("Image downloaded successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public static File downloadFile(String urlPath, String downloadDir) {
        File file = null;
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            //设置超时
            httpURLConnection.setConnectTimeout(1000*5);
            //设置请求方式，默认是GET
            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect();
            // 文件大小
            int fileLength = httpURLConnection.getContentLength();

            // 控制台打印文件大小
            System.out.println("您要下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");

            // 建立链接从请求中获取数据
            URLConnection con = url.openConnection();
            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
            // 指定文件名称(有需求可以自定义)
            String fileFullName = "aaa.jpeg";
            // 指定存放位置(有需求可以自定义)
            String path = downloadDir + File.separatorChar + fileFullName;
            file = new File(path);
            // 校验文件夹目录是否存在，不存在就创建一个目录
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            OutputStream out = new FileOutputStream(file);
            int size = 0;
            int len = 0;
            byte[] buf = new byte[2048];
            while ((size = bin.read(buf)) != -1) {
                len += size;
                out.write(buf, 0, size);
                // 控制台打印文件下载的百分比情况
                System.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
            }
            // 关闭资源
            bin.close();
            out.close();
            System.out.println("文件下载成功！");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("文件下载失败！");
        } finally {
            return file;
        }

    }
}
